﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IService;
using Entity;
using Microsoft.AspNetCore.Http;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Newtonsoft.Json;
using XingWeiDaWMSProject.IService;

namespace XingWeiDaWMSProject.Controllers
{
    public class InventoryCheckController : Controller
    {
        private readonly IInventoryService _inventoryService;
        private readonly INumberingRuleService _numberingRuleService;
        private readonly IWarehouseService _warehouseService;
        private readonly IProductInformationService _productService;
        private readonly ISysOrgUserManagementService _sysOrgUserService;

        public InventoryCheckController(
            IInventoryService inventoryService,
            INumberingRuleService numberingRuleService,
            IWarehouseService warehouseService,
            IProductInformationService productService,
            ISysOrgUserManagementService sysOrgUserService)
        {
            _inventoryService = inventoryService;
            _numberingRuleService = numberingRuleService;
            _warehouseService = warehouseService;
            _productService = productService;
            _sysOrgUserService = sysOrgUserService;
            Console.WriteLine("InventoryCheckController初始化完成");
        }

        // 统一的当前用户获取方法
        private string GetCurrentUser()
        {
            var user = HttpContext.Session.GetString("CurrentUser");
            if (string.IsNullOrEmpty(user))
            {
                user = User.Identity?.Name;
                if (string.IsNullOrEmpty(user))
                {
                    user = "admin";
                }
            }
            Console.WriteLine($"获取当前用户：{user}");
            return user;
        }

        #region 页面跳转
        public IActionResult Index()
        {
            Console.WriteLine("进入InventoryCheck/Index页面");
            return View();
        }

        public IActionResult Detail(int id)
        {
            Console.WriteLine($"进入InventoryCheck/Detail页面，ID: {id}");
            try
            {
                var inventory = _inventoryService.GetInventoryListByIdAsync(id).Result;
                if (inventory == null)
                {
                    TempData["ErrorMsg"] = "未找到指定的盘点单";
                    return View();
                }
                ViewBag.Inventory = inventory;
                return View();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Detail页面初始化异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                TempData["ErrorMsg"] = "页面加载失败，请重试";
                return View();
            }
        }
        #endregion

        #region 数据接口

        // 修正的请求模型 - 确保字段类型正确
        public class FlatInventoryRequest
        {
            public string inventory_order_no { get; set; }
            public string inventory_types { get; set; }
            public string inventory_start_time { get; set; }
            public string stkt_end_time { get; set; }
            public string warehouse_name { get; set; }
            public string handler_id { get; set; }
            public string note { get; set; }
            public int review_status { get; set; }

            // 修正字段类型 - 与前端保持一致
            public int total_profit_num { get; set; }           // 改为 int
            public int total_loss_num { get; set; }             // 改为 int
            public decimal total_profit_amount { get; set; }    // 改为 decimal（非可空）
            public decimal total_loss_amount { get; set; }      // 改为 decimal（非可空）

            public string outbound_status { get; set; } = "0";
            public List<InventoryDetailsEntity> details { get; set; }
            public string reviewer { get; set; }
        }

        // 创建盘点单 - 核心修正方法
        [HttpPost]
        public async Task<IActionResult> CreateInventory([FromBody] FlatInventoryRequest request)
        {
            try
            {
                Console.WriteLine("=== CreateInventory 方法开始 ===");

                // 详细记录接收到的数据
                Console.WriteLine("📥 接收到的请求数据:");
                Console.WriteLine($"盘盈数量: {request.total_profit_num}");
                Console.WriteLine($"盘亏数量: {request.total_loss_num}");
                Console.WriteLine($"盘盈金额: {request.total_profit_amount}");
                Console.WriteLine($"盘亏金额: {request.total_loss_amount}");
                Console.WriteLine($"明细条数: {request.details?.Count ?? 0}");

                if (request == null)
                {
                    Console.WriteLine("❌ 错误：request 为 null");
                    return Ok(new { success = false, message = "请求数据不能为空" });
                }

                // 验证必填字段
                if (string.IsNullOrEmpty(request.inventory_order_no))
                {
                    Console.WriteLine("❌ 错误：盘点单号为空");
                    return Ok(new { success = false, message = "盘点单号不能为空" });
                }
                if (string.IsNullOrEmpty(request.warehouse_name))
                {
                    Console.WriteLine("❌ 错误：仓库名称为空");
                    return Ok(new { success = false, message = "仓库名称不能为空" });
                }
                if (string.IsNullOrEmpty(request.handler_id))
                {
                    Console.WriteLine("❌ 错误：经办人为空");
                    return Ok(new { success = false, message = "经办不能为空" });
                }

                // 获取当前用户信息
                var currentUser = GetCurrentUser();
                Console.WriteLine($"创建盘点单，创建人：{currentUser}，单号：{request.inventory_order_no}");

                // 获取组织ID
                int? orgId = null;
                try
                {
                    orgId = await _sysOrgUserService.GetCurrentUserOrganizationIdAsync(currentUser);
                    Console.WriteLine($"当前用户「{currentUser}」的组织ID：{orgId}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"❌ 获取用户组织ID失败：{ex.Message}");
                    return Ok(new { success = false, message = ex.Message });
                }

                if (!orgId.HasValue)
                {
                    string errorMsg = $"用户「{currentUser}」未配置有效的组织ID，请联系管理员";
                    Console.WriteLine($"❌ {errorMsg}");
                    return Ok(new { success = false, message = errorMsg });
                }

                // 转换为实体对象 - 关键修正部分
                var mainEntity = new InventoryListEntity
                {
                    inventory_order_no = request.inventory_order_no,
                    inventory_types = request.inventory_types ?? "",
                    inventory_start_time = !string.IsNullOrEmpty(request.inventory_start_time)
                        ? DateTime.Parse(request.inventory_start_time)
                        : (DateTime?)null,
                    stkt_end_time = !string.IsNullOrEmpty(request.stkt_end_time)
                        ? DateTime.Parse(request.stkt_end_time)
                        : (DateTime?)null,
                    warehouse_name = request.warehouse_name,
                    handler_id = request.handler_id?.ToString() ?? "",
                    note = request.note ?? "",
                    review_status = 1, // 待审核状态

                    // 直接赋值，确保数据正确传递
                    total_profit_num = request.total_profit_num,
                    total_loss_num = request.total_loss_num,
                    total_profit_amount = request.total_profit_amount,
                    total_loss_amount = request.total_loss_amount,

                    create_by = currentUser ?? "system",
                    create_time = DateTime.Now,
                    is_delete = "0",
                    outbound_status = "0",
                    storage_status = 0,
                    organizations_id = orgId.Value,
                    reviewer = request.reviewer ?? "",
                    update_by = currentUser ?? "system",
                    update_time = DateTime.Now
                };

                Console.WriteLine("✅ 实体对象创建完成，开始调用服务层...");

                // 检查明细数据
                if (request.details != null && request.details.Any())
                {
                    Console.WriteLine("📋 明细数据详情:");

                    Console.WriteLine($"  共 {request.details.Count} 条明细");
                }

                var result = await _inventoryService.CreateInventoryListAsync(mainEntity, request.details ?? new List<InventoryDetailsEntity>());

                Console.WriteLine("✅ 盘点单创建成功");
                return Ok(new { success = true, data = result, message = "创建成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ CreateInventory异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Ok(new { success = false, message = $"创建失败：{ex.Message}" });
            }
        }

        // 获取盘点单列表
        [HttpPost]
        public async Task<IActionResult> GetInventoryList([FromForm] InventoryListQueryParams queryParams)
        {
            Console.WriteLine($"开始调用GetInventoryList，查询参数：{JsonConvert.SerializeObject(queryParams)}");
            try
            {
                var result = await _inventoryService.GetInventoryListAsync(queryParams);
                Console.WriteLine($"GetInventoryList查询成功，总条数：{result.Total}");
                return Json(new
                {
                    success = true,
                    total = result.Total,
                    data = result.Data
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetInventoryList异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 获取单个盘点单
        [HttpGet]
        public async Task<IActionResult> GetInventoryById(int id)
        {
            Console.WriteLine($"开始调用GetInventoryById，ID: {id}");
            try
            {
                var entity = await _inventoryService.GetInventoryListByIdAsync(id);
                Console.WriteLine($"GetInventoryById查询成功，ID: {id}");
                return Json(new { success = true, data = entity });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetInventoryById异常（ID: {id}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 生成盘点单号
        [HttpPost]
        public IActionResult GenerateBusinessNumber()
        {
            Console.WriteLine("=== 开始调用GenerateBusinessNumber ===");
            try
            {
                string targetFormName = "盘点单";
                Console.WriteLine($"准备查询表单名称为「{targetFormName}」的编号规则");

                if (string.IsNullOrWhiteSpace(targetFormName))
                {
                    string errorMsg = "目标表单名称不能为空";
                    Console.WriteLine($"GenerateBusinessNumber失败：{errorMsg}");
                    return Json(new { success = false, message = errorMsg });
                }

                NumberingRule rule;
                try
                {
                    rule = _numberingRuleService.GetByTargetFormName(targetFormName);
                    Console.WriteLine($"成功获取规则：ID={rule.rule_id}，表单名称={rule.target_form}");
                }
                catch (KeyNotFoundException ex)
                {
                    string errorMsg = $"未找到表单名称为「{targetFormName}」的编号规则，请联系管理员配置";
                    Console.WriteLine($"GenerateBusinessNumber失败：{errorMsg}（原始异常：{ex.Message}）");
                    return Json(new { success = false, message = errorMsg });
                }

                var currentUser = GetCurrentUser();
                string businessNumber = _numberingRuleService.GenerateBusinessNumber(rule.rule_id, currentUser);
                Console.WriteLine($"盘点单号生成成功：{businessNumber}（规则ID={rule.rule_id}）");
                return Json(new { success = true, businessNumber = businessNumber });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GenerateBusinessNumber异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = $"生成编号失败：{ex.Message}" });
            }
        }

        // 更新盘点单
        [HttpPost]
        public async Task<IActionResult> UpdateInventory([FromForm] InventoryListEntity main, [FromForm] List<InventoryDetailsEntity> details)
        {
            Console.WriteLine($"开始调用UpdateInventory，主单ID: {main.inventory_list_id}，明细条数：{details?.Count ?? 0}");
            try
            {
                main.update_by = GetCurrentUser();
                main.handler_id = main.handler_id?.ToString();
                Console.WriteLine($"更新盘点单，更新人：{main.update_by}，单号：{main.inventory_order_no}");
                await _inventoryService.UpdateInventoryListAsync(main, details);
                Console.WriteLine($"盘点单更新成功，ID: {main.inventory_list_id}");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"UpdateInventory异常（ID: {main.inventory_list_id}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 提交审核
        [HttpPost]
        public async Task<IActionResult> SubmitReview(int listId)
        {
            Console.WriteLine($"开始调用SubmitReview，盘点单ID: {listId}");
            try
            {
                await _inventoryService.UpdateInventoryListStatusAsync(listId, InventoryListEntity.STATUS_PENDING_REVIEW);
                Console.WriteLine($"盘点单提交审核成功，ID: {listId}");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"SubmitReview异常（ID: {listId}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 单条作废
        [HttpPost]
        public async Task<IActionResult> CancelInventory(int id)
        {
            Console.WriteLine($"开始调用CancelInventory，ID: {id}");
            try
            {
                await _inventoryService.CancelInventoryListAsync(id);
                Console.WriteLine($"盘点单作废成功，ID: {id}");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CancelInventory异常（ID: {id}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 批量作废
        [HttpPost]
        public async Task<IActionResult> BatchCancelInventory([FromForm] List<int> listIds)
        {
            Console.WriteLine($"开始调用BatchCancelInventory，ID列表：{string.Join(',', listIds)}");
            try
            {
                await _inventoryService.BatchCancelInventoryListAsync(listIds);
                Console.WriteLine($"批量作废成功，共{listIds.Count}条");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"BatchCancelInventory异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 单条删除
        [HttpPost]
        public async Task<IActionResult> DeleteInventory(int id)
        {
            Console.WriteLine($"开始调用DeleteInventory，ID: {id}");
            try
            {
                await _inventoryService.DeleteInventoryListAsync(id);
                Console.WriteLine($"盘点单删除成功，ID: {id}");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"DeleteInventory异常（ID: {id}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 批量删除
        [HttpPost]
        public async Task<IActionResult> BatchDeleteInventory([FromForm] List<int> listIds)
        {
            Console.WriteLine($"开始调用BatchDeleteInventory，ID列表：{string.Join(',', listIds)}");
            try
            {
                await _inventoryService.BatchDeleteInventoryListAsync(listIds);
                Console.WriteLine($"批量删除成功，共{listIds.Count}条");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"BatchDeleteInventory异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 锁定仓库
        [HttpPost]
        public async Task<IActionResult> LockWarehouse([FromForm] List<string> warehouseNames)
        {
            Console.WriteLine($"开始调用LockWarehouse，仓库列表：{string.Join(',', warehouseNames)}");
            try
            {
                foreach (var name in warehouseNames)
                {
                    Console.WriteLine($"锁定仓库：{name}");
                    await _inventoryService.LockWarehouseAsync(name);
                }
                Console.WriteLine($"仓库锁定成功，共{warehouseNames.Count}个");
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"LockWarehouse异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 导出数据
        [HttpGet]
        public async Task<IActionResult> ExportInventoryList(string orderNo, string reviewStatus, string warehouseName, string checkType)
        {
            Console.WriteLine($"开始调用ExportInventoryList，参数：订单号={orderNo}，状态={reviewStatus}，仓库={warehouseName}，类型={checkType}");
            try
            {
                int? reviewStatusInt = null;
                if (!string.IsNullOrEmpty(reviewStatus) && int.TryParse(reviewStatus, out int status))
                {
                    reviewStatusInt = status;
                }

                var queryParams = new InventoryListQueryParams
                {
                    OrderNo = orderNo,
                    ReviewStatus = reviewStatusInt,
                    WarehouseName = warehouseName,
                    CheckType = checkType,
                    PageIndex = 1,
                    PageSize = int.MaxValue
                };

                var result = await _inventoryService.GetInventoryListAsync(queryParams);
                var data = result.Data;
                Console.WriteLine($"导出数据查询完成，总条数：{data.Count}");

                byte[] fileBytes;
                using (var stream = new MemoryStream())
                {
                    IWorkbook workbook = new XSSFWorkbook();
                    ISheet sheet = workbook.CreateSheet("盘点单列表");

                    var headerRow = sheet.CreateRow(0);
                    var headers = new List<string> {
                        "盘点单号", "盘点类型", "仓库名称", "盘点结果",
                        "开始时间", "结束时间", "制单人", "制单时间",
                        "盘盈数量", "盘亏数量", "盘盈金额", "盘亏金额"
                    };
                    for (int i = 0; i < headers.Count; i++)
                    {
                        headerRow.CreateCell(i).SetCellValue(headers[i]);
                    }

                    for (int i = 0; i < data.Count; i++)
                    {
                        var row = sheet.CreateRow(i + 1);
                        var item = data[i];
                        row.CreateCell(0).SetCellValue(item.inventory_order_no);
                        row.CreateCell(1).SetCellValue(item.inventory_types);
                        row.CreateCell(2).SetCellValue(item.warehouse_name);
                        row.CreateCell(3).SetCellValue(GetStatusText(item.review_status));
                        row.CreateCell(4).SetCellValue(item.inventory_start_time.HasValue
                            ? item.inventory_start_time.Value.ToString("yyyy-MM-dd HH:mm:ss")
                            : "");
                        row.CreateCell(5).SetCellValue(item.stkt_end_time.HasValue
                            ? item.stkt_end_time.Value.ToString("yyyy-MM-dd HH:mm:ss")
                            : "");
                        row.CreateCell(6).SetCellValue(item.create_by);
                        row.CreateCell(7).SetCellValue(item.create_time.HasValue
                            ? item.create_time.Value.ToString("yyyy-MM-dd HH:mm:ss")
                            : "");
                        row.CreateCell(8).SetCellValue(item.total_profit_num ?? 0);
                        row.CreateCell(9).SetCellValue(item.total_loss_num ?? 0);
                        row.CreateCell(10).SetCellValue(item.total_profit_amount.HasValue
                            ? item.total_profit_amount.Value.ToString("F2")
                            : "0.00");
                        row.CreateCell(11).SetCellValue(item.total_loss_amount.HasValue
                            ? item.total_loss_amount.Value.ToString("F2")
                            : "0.00");
                    }

                    for (int i = 0; i < headers.Count; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }

                    workbook.Write(stream);
                    fileBytes = stream.ToArray();
                }

                Console.WriteLine($"Excel生成成功，文件大小：{fileBytes.Length}字节");
                return File(
                    fileBytes,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    $"盘点单列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                );
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ExportInventoryList异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 获取盘点明细
        [HttpGet]
        public async Task<IActionResult> GetDetails(int listId)
        {
            Console.WriteLine($"开始调用GetDetails，盘点单ID: {listId}");
            try
            {
                var details = await _inventoryService.GetInventoryDetailsByListIdAsync(listId);
                Console.WriteLine($"获取明细成功，ID: {listId}，条数：{details.Count}");
                return Json(new { success = true, data = details });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetDetails异常（ID: {listId}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }
        #endregion

        #region 基础数据接口
        // 新增页面路由
        public IActionResult Add(int? id)
        {
            Console.WriteLine($"进入InventoryCheck/Add页面，ID: {id ?? -1}");
            ViewBag.Id = id;
            return View();
        }

        // 获取所有仓库
        [HttpGet]
        public async Task<IActionResult> GetAllWarehouses()
        {
            Console.WriteLine("开始调用GetAllWarehouses");
            try
            {
                var warehouses = await _inventoryService.GetAllWarehousesAsync();
                Console.WriteLine($"获取仓库列表成功，条数：{warehouses.Count}");
                return Json(new { success = true, data = warehouses });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetAllWarehouses异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 获取所有用户（经办人）
        [HttpGet]
        public async Task<IActionResult> GetAllUsers()
        {
            Console.WriteLine("开始调用GetAllUsers");
            try
            {
                var users = await _warehouseService.GetAllUsers();
                Console.WriteLine($"获取用户列表成功，条数：{users.Count}");
                return Json(new { success = true, data = users });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetAllUsers异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        [HttpGet]
        public async Task<IActionResult> Search([FromQuery] ProductSearchParam param, string location = null)
        {
            var queryString = HttpContext.Request.QueryString.ToString();
            Console.WriteLine($"=== 搜索货品请求开始 ===");
            Console.WriteLine($"完整查询字符串: {queryString}");
            Console.WriteLine($"解析后的参数 - Keyword: '{param.Keyword}', PageNum: {param.PageNum}, PageSize: {param.PageSize}, WarehouseName: '{param.WarehouseName}', Location: '{location}'");

            try
            {
                // 使用统一的方法调用
                var result = await _productService.SearchAsync(param, location: location);
                Console.WriteLine($"货品搜索成功，总条数：{result.Total}");
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Search货品异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
            finally
            {
                Console.WriteLine($"=== 搜索货品请求结束 ===");
            }
        }

        [HttpGet]
        public IActionResult Test()
        {
            Console.WriteLine("测试路由被调用");
            return Json(new { success = true, message = "路由测试成功" });
        }

        // 检查仓库锁定状态
        [HttpGet]
        public async Task<IActionResult> CheckWarehouseLock(string warehouseName)
        {
            Console.WriteLine($"开始调用CheckWarehouseLock，仓库名称: {warehouseName}");
            try
            {
                if (string.IsNullOrEmpty(warehouseName))
                {
                    Console.WriteLine("仓库名称为空，返回未锁定状态");
                    return Json(new { success = true, isLocked = false });
                }

                var isLocked = await _inventoryService.CheckWarehouseLockAsync(warehouseName);
                Console.WriteLine($"仓库 '{warehouseName}' 锁定状态: {isLocked}");
                return Json(new { success = true, isLocked = isLocked });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CheckWarehouseLock异常（仓库: {warehouseName}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message, isLocked = false });
            }
        }

        // 获取所有库位
        [HttpGet]
        public async Task<IActionResult> GetAllStorageLocations()
        {
            Console.WriteLine("开始调用GetAllStorageLocations");
            try
            {
                var locations = await _inventoryService.GetAllStorageLocationsAsync();
                Console.WriteLine($"获取库位列表成功，条数：{locations.Count}");
                return Json(new { success = true, data = locations });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetAllStorageLocations异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 根据仓库名称获取库位
        [HttpGet]
        public async Task<IActionResult> GetStorageLocationsByWarehouse(string warehouseName)
        {
            Console.WriteLine($"开始调用GetStorageLocationsByWarehouse，仓库名称: {warehouseName}");
            try
            {
                var locations = await _inventoryService.GetStorageLocationsByWarehouseAsync(warehouseName);
                Console.WriteLine($"获取仓库 '{warehouseName}' 的库位列表成功，条数：{locations.Count}");
                return Json(new { success = true, data = locations });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetStorageLocationsByWarehouse异常：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 测试库位连接
        [HttpGet]
        public async Task<IActionResult> TestStorageLocationConnection()
        {
            Console.WriteLine("🔄 开始测试库位数据库连接");
            try
            {
                var result = await _warehouseService.TestStorageLocationConnection();
                return Json(new { success = true, connected = result });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 测试库位连接异常：{ex.Message}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        // 获取库位数据详情（调试用）
        [HttpGet]
        public async Task<IActionResult> GetStorageLocationsDebug()
        {
            Console.WriteLine("🔄 开始获取库位调试信息");
            try
            {
                var allLocations = await _inventoryService.GetAllStorageLocationsAsync();
                var testConnection = await _warehouseService.TestStorageLocationConnection();

                return Json(new
                {
                    success = true,
                    connectionTest = testConnection,
                    totalCount = allLocations.Count,
                    data = allLocations,
                    sampleData = allLocations.Take(3).ToList()
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 获取库位调试信息异常：{ex.Message}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 审核盘点单并更新库存
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ApproveInventory(int id, string reviewer)
        {
            Console.WriteLine($"开始审核盘点单，ID: {id}，审核人: {reviewer}");
            try
            {
                if (string.IsNullOrEmpty(reviewer))
                {
                    reviewer = GetCurrentUser();
                }

                Console.WriteLine($"审核人：{reviewer}，盘点单ID: {id}");

                // 直接调用服务层的审核方法
                await _inventoryService.ApproveInventoryAsync(id, reviewer);

                Console.WriteLine($"盘点单审核成功，ID: {id}，库存已更新");
                return Json(new
                {
                    success = true,
                    message = "审核成功，已更新库存"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"ApproveInventory异常（ID: {id}）：{ex.Message}\n堆栈：{ex.StackTrace}");
                return Json(new { success = false, message = $"审核失败：{ex.Message}" });
            }
        }
        // 在 InventoryCheckController 中修改
        [HttpGet]
        public async Task<IActionResult> GetProductStocks(string productCodes, string warehouseName = null, string location = null)
        {
            Console.WriteLine($"开始调用GetProductStocks，货品编号: {productCodes}，仓库: {warehouseName}，库位: {location}");
            try
            {
                if (string.IsNullOrEmpty(productCodes))
                {
                    return Json(new { success = true, data = new Dictionary<string, int>() });
                }

                var codes = productCodes.Split(',').Where(c => !string.IsNullOrEmpty(c)).ToList();
                var stockDict = new Dictionary<string, int>();

                foreach (var code in codes)
                {
                    try
                    {
                        // 如果有库位参数，按库位查询
                        if (!string.IsNullOrEmpty(location))
                        {
                            var stock = await _inventoryService.GetCurrentStockByProductAndLocationAsync(code, warehouseName, location);
                            stockDict[code] = stock;
                            Console.WriteLine($"货品 {code} 在库位 {location} 的当前库存: {stock} (仓库: {warehouseName})");
                        }
                        else
                        {
                            // 没有库位参数，按原有逻辑查询
                            var stock = await _inventoryService.GetCurrentStockByProductCodeAsync(code, warehouseName);
                            stockDict[code] = stock;
                            Console.WriteLine($"货品 {code} 当前库存: {stock} (仓库: {warehouseName})");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"获取货品 {code} 库存失败: {ex.Message}");
                        stockDict[code] = 0;
                    }
                }

                return Json(new { success = true, data = stockDict });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"GetProductStocks异常: {ex.Message}\n堆栈: {ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        #endregion

        #region 辅助方法
        private string GetStatusText(int status)
        {
            var map = new Dictionary<int, string>
            {
                {0, "草稿"}, {1, "待审核"}, {2, "有盈亏"}, {3, "无盈亏"}, {4, "已作废"}
            };
            var text = map.TryGetValue(status, out var val) ? val : status.ToString();
            Console.WriteLine($"状态码转换：{status} -> {text}");
            return text;
        }
        #endregion
    }
}